package com.leetcodehot.problems;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class problems2641 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 暴力：每一层的sum再第二遍逐层判断
     */
    public TreeNode replaceValueInTree(TreeNode root) {
        root.val = 0;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.addLast(root);
        while (!deque.isEmpty()) {
            Deque<TreeNode> temp = new ArrayDeque<>(deque);
            deque.clear();
            int nextLevelSum = 0;
            for (TreeNode node : temp) {
                if (node.left != null) {
                    deque.addLast(node.left);
                    nextLevelSum += node.left.val;
                }
                if (node.right != null) {
                    deque.addLast(node.right);
                    nextLevelSum += node.right.val;
                }
            }
            for (TreeNode node : temp) {
                int childSum = (node.left != null ? node.left.val : 0) + (node.right != null ? node.right.val : 0);
                if (node.left != null) node.left.val = nextLevelSum - childSum;
                if (node.right != null) node.right.val = nextLevelSum - childSum;
            }
        }
        return root;
    }
}
